package com.shunya.diskorganizer;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;

public class CheckSumGenerator {
    public static long computeCRC32CheckSum(InputStream inputStream) throws IOException {
        return getChecksumForFile(inputStream, new CRC32());
    }

    public static long computeAdler32CheckSum(InputStream inputStream) throws IOException {
        return getChecksumForFile(inputStream, new Adler32());
    }

    public static String computeMD5Hash(InputStream inputStream) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        inputStream = new DigestInputStream(inputStream, md);
        readFileContents(inputStream);
        return new BigInteger(md.digest()).toString(16);
    }

    private static long getChecksumForFile(InputStream inputStream, Checksum checksumAlgorithm) throws IOException {
        CheckedInputStream cis = new CheckedInputStream(inputStream, checksumAlgorithm);
        readFileContents(cis);
        return cis.getChecksum().getValue();
    }

    private static void readFileContents(InputStream inputStream) throws IOException {
        byte[] tempBuf = new byte[1024];
        while (inputStream.read(tempBuf) >= 0);
    }


}
